package controllers;

import java.util.List;

import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Date;

import models.Entities;
import models.IdeaDeveloper;
import models.Log;
import models.Notification;
import models.Organization;
import models.OrganizationLead;
import models.Organizer;
import models.Picture;
import models.Request;
import play.db.jpa.Blob;
import play.mvc.Controller;
import play.mvc.With;

@With(Secure.class)
public class UsersController extends Controller {
	/**
	 * renders the EditUser page
	 */
	public static void EditUser() {
		IdeaDeveloper karim = null;
		if (IdeaDeveloper.find("username = ?", "Karim").fetch().size() == 1) {
			karim = (IdeaDeveloper) IdeaDeveloper.find("username = ?", "Karim")
					.fetch().get(0);

		} else {
			karim = new IdeaDeveloper("Karim", "Karim", "123", "123", "123",
					"123");
			karim.theme = "blue";
			karim.eMail = "Karim.abdo.1991@gmail.com";
			karim.save();
		}
		String usercurrent = karim.username;
		// usercurrent = Security.connected();
		render(usercurrent);
	}

	/**
	 * Renders the userrequests page
	 */
	public static void UserRequests() {
		IdeaDeveloper karim = null;
		if (IdeaDeveloper.find("username = ?", "Karim").fetch().size() == 1) {
			karim = (IdeaDeveloper) IdeaDeveloper.find("username = ?", "Karim")
					.fetch().get(0);

		} else {
			karim = new IdeaDeveloper("Karim", "Karim", "123", "123", "123",
					"123");
			karim.theme = "blue";
			karim.eMail = "Karim.abdo.1991@gmail.com";
			karim.save();
		}
		String usercurrent = karim.username;
		// usercurrent = Security.connected();
		render(usercurrent);
	}

	public static void LogView(long organizationId) {
		render(organizationId);
	}

	/**
	 * renders the notification page
	 */
	public static void notification() {
		IdeaDeveloper karim = null;
		if (IdeaDeveloper.find("username = ?", "Karim").fetch().size() == 1) {
			karim = (IdeaDeveloper) IdeaDeveloper.find("username = ?", "Karim")
					.fetch().get(0);

		} else {
			karim = new IdeaDeveloper("Karim", "Karim", "123", "123", "123",
					"123");
			karim.theme = "blue";
			karim.eMail = "Karim.abdo.1991@gmail.com";
			karim.save();
		}
		String usercurrent = karim.username;
		render(usercurrent);
	}

	/**
	 *  views the log of the whole system
	 * 
	 */
	public static void viewLog(long organizationId) {

		List<Log> logTable = Log.searchLog("organization",
				(long) organizationId);
		String[] logArray = new String[logTable.size()];

		for (Log logEntry : logTable) {
			if (!Log.decode(logEntry).equals("")) {
				logArray[logTable.indexOf(logEntry)] = Log.decode(logEntry)
						+ "^#^" + logEntry.date;
			}
		}
		renderJSON(logArray);
	}

	/**
	 *  load user information ( address, theme and image)
	 * 
	 * @author KimO
	 * 
	 * @param currentUser
	 *            the user that will edit the information
	 * @param username
	 *            the user name of the idea developer whose data will be changed
	 * @param newAddress
	 *            the new address that will replace the old address
	 * @param newTheme
	 *            the new theme chosen
	 * @param newImagePath
	 *            the new profile image path
	 */
	public static void editUserInfo(String currentUser, String username) {
		JsonObject json = new JsonObject();

		try {
			IdeaDeveloper ideadev = (IdeaDeveloper) IdeaDeveloper.find(
					"username = ?", username).first();
			json.addProperty("username", username);
			json.addProperty("address", ideadev.address);
			json.addProperty("theme", ideadev.theme);
			json.addProperty("email", ideadev.eMail);
			renderJSON(json.toString());
		} catch (Exception e) {
			renderJSON("Error");
		}
	}

	/**
	 *  renders the page where the user can invite friend by sending
	 * an email containing the link to the Registration page
	 */
	public static void InviteFriend() {
		IdeaDeveloper karim = null;
		if (IdeaDeveloper.find("username = ?", "Karim").fetch().size() == 1) {
			karim = (IdeaDeveloper) IdeaDeveloper.find("username = ?", "Karim")
					.fetch().get(0);

		} else {
			karim = new IdeaDeveloper("Karim", "Karim", "123", "123", "123",
					"123");
			karim.theme = "blue";
			karim.eMail = "Karim.abdo.1991@gmail.com";
			karim.save();
		}
		String usercurrent = karim.username;
		// usercurrent = Security.connected();
		render(usercurrent);
	}

	/**
	 *  saves the edited info in the idea developer table
	 * 
	 * @author KimO
	 * 
	 * @param currentUser
	 *            the user that will edit the information
	 * @param username
	 *            the user name of the idea developer whose data will be changed
	 * @param newAddress
	 *            the new address that will replace the old address
	 * @param newTheme
	 *            the new theme chosen
	 * @param newImagePath
	 *            the new profile image path
	 */
	public static void saveUserInfoEdited(String currentUser, String username,
			String newAddress, String newTheme/* , Blob newImagePath */,
			String eMail) {
		IdeaDeveloper ideadev = (IdeaDeveloper) IdeaDeveloper
				.find("username = ?", username).fetch().get(0);
		String res = ideadev.editUserInformation(username, currentUser,
				newAddress, 0, eMail);
		JsonObject json = new JsonObject();
		json.addProperty("done", res);
		renderJSON(json.toString());
	}

	/**
	 *  is used to send an email to an unregistered user to invite
	 * him to the application after checking that he is not a registered user
	 *
	 * @author KimO
	 * @param currentUser
	 *            the user inviting
	 * @param eMail
	 *            the email of the person who will be invited
	 * @throws EmailException
	 *             to work :D
	 */
	public static void invitationSending(String currentUser, String eMail) {
		IdeaDeveloper ideaDev = (IdeaDeveloper) IdeaDeveloper
				.find("username = ?", currentUser).fetch().get(0);
		IdeaDeveloper.sendInvitationMail(ideaDev.fullName, eMail);
		JsonObject json = new JsonObject();
		json.addProperty("res", "done");
		renderJSON(json);
	}

	/**
	 *  is used to return the Big notification list of an
	 * Organization
	 * 
	 * @author sherif
	 * 
	 * @param orgName
	 *            The name of the organization
	 * 
	 */
	public static void DisplayNotificationBOrg(String orgName) {
		JsonObject json = new JsonObject();

		Organization org = (Organization) Organization
				.find("username = ?", orgName).fetch().get(0);
		List<Notification> notifications = org.notifications;
		if (notifications.isEmpty()) {
			json.addProperty("result", "sizeEqualZero");
		} else {
			json.addProperty("result", "sizeNotEqualZero");

			String listOfNotifications = "";
			for (Notification notification : org.notifications) {

				listOfNotifications += notification.sender.username + ",,,"
						+ notification.body + ",,," + "&&";
			}
			json.addProperty("list", listOfNotifications);
		}
		renderJSON(json);
	}

	/**
	 *  is used to return the small notification list of an idea
	 * developer
	 * 
	 * @author sherif
	 * 
	 * @param userName
	 *            The name of the user
	 * 
	 */
	public static void DisplayNotificationSID(String userName) {
		// IdeaDeveloper karim = (IdeaDeveloper) IdeaDeveloper
		// .find("username = ?", userName).fetch().get(0);
		// ;
		IdeaDeveloper ideaDev = null;
		Notification N;
		// IdeaDeveloper sherif = new IdeaDeveloper();
		JsonObject json = new JsonObject();
		String listOfNotifications = "";
		// sherif.username = "sherif";
		// sherif.fullName = "sherif";
		// sherif.eMail = "email2@email.com";
		// sherif.dateOfBirth = "1/1/2000";
		// sherif.password = "pass";
		// sherif.passwordHash = "hash";
		// sherif.address = "add";
		// sherif.theme = "blue";
		// sherif.save();
		// Notification.notify("has updated his profile", karim, sherif,
		// new Date());
		// karim.save();
		// sherif.save();
		// Notification.notify("has updated his profile", sherif, karim,
		// new Date());
		//
		// karim.save();
		// sherif.save();
		// Notification.notify("has added a new idea", karim, sherif, new
		// Date());
		// karim.save();
		// sherif.save();
		// Notification.notify("has added a new idea", sherif, karim, new
		// Date());
		//
		// karim.save();
		// sherif.save();
		// Notification.notify("has created a new entity", karim, sherif,
		// new Date());
		// karim.save();
		// sherif.save();
		// Notification.notify("has created a new entity", sherif, karim,
		// new Date());
		//
		// karim.save();
		// sherif.save();

		userName = Security.connected();
		List temp = IdeaDeveloper.find("username = ?", userName).fetch();
		if (IdeaDeveloper.find("username = ?", userName).fetch().size() == 1) {
			ideaDev = (IdeaDeveloper) IdeaDeveloper
					.find("username = ?", userName).fetch().get(0);

			if (ideaDev.notifications != null) {
				if (ideaDev.notifications.isEmpty()) {
					// listOfNotifications+=IdeaDeveloper.find("username = ?",
					// userName).fetch().size();
					// listOfNotifications+=IdeaDeveloper.find("username = ?",
					// userName).fetch().get(0).toString();
					// json.addProperty("result", listOfNotifications);
					// renderJSON(json.toString());
				} else {
					json.addProperty("result", "sizeNotEqualZero");
					for (int i = 0; i < ideaDev.notifications.size(); i++) {
						listOfNotifications += ideaDev.notifications
								.get(ideaDev.notifications.size() - i - 1).sender.username
								+ ",,,"
								+ ideaDev.notifications
										.get(ideaDev.notifications.size() - i
												- 1).body
								+ ",,,"
								+ ideaDev.notifications
										.get(ideaDev.notifications.size() - i
												- 1).date.getTime()
								+ ",,,"
								+ "&&";
					}
					json.addProperty("list", listOfNotifications);

					renderJSON(json.toString());
				}
			}
		} else {
			// karim.username= "Karim";
			// karim.fullName = "DinaTarek";
			// karim.eMail = "email@email.com";
			// karim.dateOfBirth = "1/1/2000";
			// karim.password = "pass";
			// karim.passwordHash = "hash";
			// karim.address = "add";
			//
			// karim.save();
		}

	}

	/**
	 *  is used to return the notification popup displayed to an idea
	 * developer
	 * 
	 * @author sherif
	 * 
	 * @param userName
	 *            The name of the user
	 * 
	 */
	public static void DisplayNotificationPopID(String userName) {
		// IdeaDeveloper karim = (IdeaDeveloper) IdeaDeveloper
		// .find("username = ?", userName).fetch().get(0);
		// ;
		IdeaDeveloper ideaDev = null;
		Notification N;

		JsonObject json = new JsonObject();
		String listOfNotifications = "";

		userName = Security.connected();
		List temp = IdeaDeveloper.find("username = ?", userName).fetch();
		List<Notification> notifications = new ArrayList<Notification>();
		if (IdeaDeveloper.find("username = ?", userName).fetch().size() == 1) {
			ideaDev = (IdeaDeveloper) IdeaDeveloper
					.find("username = ?", userName).fetch().get(0);

			if (ideaDev.notifications != null) {
				if (ideaDev.notifications.isEmpty()) {
				} else {
					json.addProperty("result", "sizeNotEqualZero");
					if (ideaDev.notifications
							.get(ideaDev.notifications.size() - 1).viewed == true) {
						json.addProperty("NoNewNotification", "yes");
						renderJSON(json.toString());
					}

					for (int i = 0; i < ideaDev.notifications.size(); i++) {
						if (ideaDev.notifications.get(i).viewed == false) {
							ideaDev.notifications.get(i).viewed = true;
							ideaDev.save();
							listOfNotifications += ideaDev.notifications.get(i).sender.username
									+ " "
									+ ideaDev.notifications.get(i).body
									+ " " + ".";
							break;
						}
					}
					json.addProperty("NoNewNotification", "no");
					json.addProperty("list", listOfNotifications);

					renderJSON(json.toString());
				}
			}
			// } else {
			// IdeaDeveloper sherif = new IdeaDeveloper();
			//
			// sherif.username = "sherif";
			// sherif.fullName = "sherif";
			// sherif.eMail = "email2@email.com";
			// sherif.dateOfBirth = "1/1/2000";
			// sherif.password = "pass";
			// sherif.passwordHash = "hash";
			// sherif.address = "add";
			// sherif.theme = "blue";
			// sherif.save();
			// Notification.notify("has updated his profile", karim, sherif,
			// new Date());
			// karim.save();
			// sherif.save();
			// Notification.notify("has updated his profile", sherif, karim,
			// new Date());
			//
			// karim.save();
			// sherif.save();
			// Notification.notify("has added a new idea", karim, sherif,
			// new Date());
			// karim.save();
			// sherif.save();
			// Notification.notify("has added a new idea", sherif, karim,
			// new Date());
			//
			// karim.save();
			// sherif.save();
			// Notification.notify("has created a new entity", karim, sherif,
			// new Date());
			// karim.save();
			// sherif.save();
			// Notification.notify("has created a new entity", sherif, karim,
			// new Date());
			//
			// karim.save();
			// sherif.save();
			//
			// DisplayNotificationPopID(userName);
		}

	}

	/**
	 *  splits the requests to be organizer and put them all in 1
	 * string in order to be read by the view ,,, to split inside same requests
	 * and && to split different requests
	 * 
	 * @author KimO
	 * 
	 * @param currentUser
	 *            the user who we check he has requests or not
	 */
	public static void loadRequests(String currentUser) {

		try {
			IdeaDeveloper ideadev = (IdeaDeveloper) IdeaDeveloper
					.find("username = ?", currentUser).fetch().get(0);

			JsonObject json = new JsonObject();

			json.addProperty("result", "sizeNotEqualZero");

			String listOfRequests = "";
			for (Request request : ideadev.requests) {
				if (/*
					 * (request.type.equals("JoinEntFromEntToDev")) &&
					 */(request.status.equalsIgnoreCase("new"))) {
					listOfRequests += request.dev.username + ",,,"
							+ request.type + ",,," + request.id + "AAA";
				}
				json.addProperty("list", listOfRequests);
			}
			if (listOfRequests.equals("")) {
				json.addProperty("result", "sizeEqualZero");

				// TEST
				listOfRequests += ideadev.username + ",,," + "request.body"
						+ ",,," + 1;
				listOfRequests += "AAA";
				listOfRequests += ideadev.username + "2,,," + "request.body2"
						+ ",,," + 2;
				json.addProperty("list", listOfRequests);
				// TEST
			}
			renderJSON(json.toString());

		} catch (Exception e) {
			JsonObject json = new JsonObject();
			json.addProperty("result", "Exception");
			renderJSON(json.toString());
		}
	}

	/**
	 * is used to save the users reply on the request to be
	 * organizer
	 * 
	 * @author KimO
	 * 
	 * @param decision
	 *            the decision of the user either to accept the invitation or to
	 *            reject it
	 * @param requestID
	 *            the id of the request
	 */
	public static void saveDecisionRequest(Boolean decision, long requestID) {
		JsonObject json = new JsonObject();
		Request.replyRequest(requestID, decision);
		json.addProperty("result", "done");
		renderJSON(json.toString());
	}
}
